const mockDatabase = require('../config/mockDatabase');

class ReportPermission {
  constructor(data) {
    this.id = data.id;
    this.report_key = data.report_key;
    this.role = data.role;
    this.store_id = data.store_id;
    this.region_id = data.region_id;
    this.can_view = data.can_view;
    this.can_export = data.can_export;
    this.can_subscribe = data.can_subscribe;
    this.data_scope = data.data_scope;
    this.created_at = data.created_at;
    this.updated_at = data.updated_at;
  }

  // 检查用户是否有报表访问权限
  static async checkPermission(reportKey, userRole, action = 'view', storeId = null, regionId = null) {
    try {
      const permissions = mockDatabase.reportPermissions || [];
      
      // 查找匹配的权限记录
      const permission = permissions.find(p => 
        p.report_key === reportKey && 
        p.role === userRole &&
        (p.store_id === null || p.store_id === storeId) &&
        (p.region_id === null || p.region_id === regionId)
      );
      
      if (!permission) {
        return false;
      }
      
      // 检查具体权限
      switch (action) {
        case 'view':
          return permission.can_view;
        case 'export':
          return permission.can_export;
        case 'subscribe':
          return permission.can_subscribe;
        default:
          return false;
      }
    } catch (error) {
      console.error('Error checking report permission:', error);
      return false;
    }
  }

  // 获取用户可访问的报表列表
  static async getUserAccessibleReports(userRole, storeId = null, regionId = null) {
    try {
      const permissions = mockDatabase.reportPermissions || [];
      
      // 筛选用户可查看的报表权限
      const accessiblePermissions = permissions.filter(p => 
        p.role === userRole &&
        p.can_view &&
        (p.store_id === null || p.store_id === storeId) &&
        (p.region_id === null || p.region_id === regionId)
      );
      
      return accessiblePermissions.map(p => ({
        report_key: p.report_key,
        can_export: p.can_export,
        can_subscribe: p.can_subscribe,
        data_scope: p.data_scope
      }));
    } catch (error) {
      console.error('Error getting user accessible reports:', error);
      return [];
    }
  }

  // 获取报表的权限配置
  static async getReportPermissions(reportKey) {
    try {
      const permissions = mockDatabase.reportPermissions || [];
      const reportPermissions = permissions.filter(p => p.report_key === reportKey);
      
      return reportPermissions.map(permission => new ReportPermission(permission));
    } catch (error) {
      console.error('Error getting report permissions:', error);
      throw error;
    }
  }

  // 创建新的权限配置
  static async create(permissionData) {
    try {
      if (!mockDatabase.reportPermissions) {
        mockDatabase.reportPermissions = [];
      }
      
      const newPermission = {
        id: mockDatabase.reportPermissions.length + 1,
        ...permissionData,
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString()
      };
      
      mockDatabase.reportPermissions.push(newPermission);
      return new ReportPermission(newPermission);
    } catch (error) {
      console.error('Error creating report permission:', error);
      throw error;
    }
  }

  // 更新权限配置
  static async update(id, updateData) {
    try {
      const permissions = mockDatabase.reportPermissions || [];
      const permissionIndex = permissions.findIndex(p => p.id === id);
      
      if (permissionIndex === -1) {
        throw new Error('Permission not found');
      }
      
      permissions[permissionIndex] = {
        ...permissions[permissionIndex],
        ...updateData,
        updated_at: new Date().toISOString()
      };
      
      return new ReportPermission(permissions[permissionIndex]);
    } catch (error) {
      console.error('Error updating report permission:', error);
      throw error;
    }
  }

  // 删除权限配置
  static async delete(id) {
    try {
      const permissions = mockDatabase.reportPermissions || [];
      const permissionIndex = permissions.findIndex(p => p.id === id);
      
      if (permissionIndex === -1) {
        throw new Error('Permission not found');
      }
      
      permissions.splice(permissionIndex, 1);
      return true;
    } catch (error) {
      console.error('Error deleting report permission:', error);
      throw error;
    }
  }

  // 批量设置角色权限
  static async setRolePermissions(role, reportKeys, permissions) {
    try {
      if (!mockDatabase.reportPermissions) {
        mockDatabase.reportPermissions = [];
      }
      
      const results = [];
      
      for (const reportKey of reportKeys) {
        // 查找现有权限
        const existingIndex = mockDatabase.reportPermissions.findIndex(p => 
          p.report_key === reportKey && p.role === role
        );
        
        const permissionData = {
          report_key: reportKey,
          role: role,
          ...permissions,
          updated_at: new Date().toISOString()
        };
        
        if (existingIndex >= 0) {
          // 更新现有权限
          mockDatabase.reportPermissions[existingIndex] = {
            ...mockDatabase.reportPermissions[existingIndex],
            ...permissionData
          };
          results.push(new ReportPermission(mockDatabase.reportPermissions[existingIndex]));
        } else {
          // 创建新权限
          const newPermission = {
            id: mockDatabase.reportPermissions.length + 1,
            ...permissionData,
            created_at: new Date().toISOString()
          };
          mockDatabase.reportPermissions.push(newPermission);
          results.push(new ReportPermission(newPermission));
        }
      }
      
      return results;
    } catch (error) {
      console.error('Error setting role permissions:', error);
      throw error;
    }
  }

  // 获取数据范围筛选条件
  static getDataScopeFilter(dataScope, storeId = null, regionId = null) {
    const filter = {};
    
    switch (dataScope) {
      case 'store':
        if (storeId) {
          filter.store_id = storeId;
        }
        break;
      case 'region':
        if (regionId) {
          filter.region_id = regionId;
        }
        break;
      case 'self':
        // 仅查看自己相关的数据
        filter.self_only = true;
        break;
      case 'all':
      default:
        // 无额外限制
        break;
    }
    
    return filter;
  }

  // 验证权限数据
  static validatePermission(permissionData) {
    const errors = [];
    
    if (!permissionData.report_key) {
      errors.push('report_key is required');
    }
    
    if (!permissionData.role || !['super_admin', 'admin', 'manager', 'staff', 'cashier'].includes(permissionData.role)) {
      errors.push('Valid role is required');
    }
    
    if (!permissionData.data_scope || !['all', 'region', 'store', 'self'].includes(permissionData.data_scope)) {
      errors.push('Valid data_scope is required');
    }
    
    return errors;
  }
}

module.exports = ReportPermission;